import './App.css';
import {Provider} from 'react-redux';
import {PersistGate} from 'redux-persist/integration/react';
import {RouterProvider} from 'react-router-dom';
import {Spin} from 'antd';
import store, {persistor} from './store';
import routers from './router/index.tsx';
import '@icon-park/react/styles/index.css';
import { useEffect } from 'react';
import { useDispatch } from 'react-redux';
import { getAdminUserInfo } from '@/api/userController';
import { setLoginUser } from '@/store/loginUser';
import { DEFAULT_USER } from '@/store/loginUser';
import Cookies from 'js-cookie';

// 创建一个认证检查组件
const AuthChecker = () => {
  const dispatch = useDispatch();

  useEffect(() => {
    const checkAuth = async () => {
      try {
        const res = await getAdminUserInfo();
        if (res.code !== 200) {
          // 如果响应码不是200，清除认证信息
          Cookies.remove('spring-ai-token');
          dispatch(setLoginUser(DEFAULT_USER));
        }
      } catch (error) {
        // 如果请求失败，也清除认证信息
        Cookies.remove('spring-ai-token');
        dispatch(setLoginUser(DEFAULT_USER));
      }
    };

    // 立即执行一次
    checkAuth();

    // 设置20秒的定时器
    const timer = setInterval(checkAuth, 20000);

    // 清理函数
    return () => {
      clearInterval(timer);
    };
  }, [dispatch]);

  return null;
};

// 创建一个滚动管理组件
const ScrollToTop = ({ children }: { children: React.ReactNode }) => {
  return <>{children}</>;
};

function App() {
  return (
    <Provider store={store}>
      <PersistGate loading={<Spin />} persistor={persistor}>
        <ScrollToTop>
          <AuthChecker />
          <RouterProvider router={routers} />
        </ScrollToTop>
      </PersistGate>
    </Provider>
  );
}

export default App;
